<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 客户基础数据管理
 *
 * @icon fa fa-users
 * @remark 管理客户基础信息，包括特殊生产要求等
 */
class Customer extends Backend
{
    /**
     * Customer模型对象
     * @var \app\admin\model\scanwork\Customer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Customer;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['orders'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // 添加统计信息
            $rows = [];
            foreach ($list as $item) {
                $row = $item->toArray();
                $stats = $item->getCustomerStats();
                $row['order_count'] = $stats['order_count'];
                $row['total_quantity'] = $stats['total_quantity'];
                $row['completion_rate'] = $stats['completion_rate'];
                $rows[] = $row;
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成客户编码
                if (empty($params['customer_code'])) {
                    $params['customer_code'] = $this->generateCustomerCode();
                }
                
                // 检查客户编码是否唯一
                if (!$this->model->checkCodeUnique($params['customer_code'])) {
                    $this->error('客户编码已存在');
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 检查客户编码是否唯一
                if (!$this->model->checkCodeUnique($params['customer_code'], $ids)) {
                    $this->error('客户编码已存在');
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $name;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的订单
                    $orderCount = \app\admin\model\scanwork\Order::where('customer_id', $item->id)->count();
                    if ($orderCount > 0) {
                        throw new Exception("客户【{$item->customer_name}】下还有{$orderCount}个订单，请先删除相关订单");
                    }
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取客户统计信息
        $stats = $row->getCustomerStats();
        
        // 获取客户订单列表
        $orders = \app\admin\model\scanwork\Order::where('customer_id', $ids)
            ->order('createtime desc')
            ->limit(20)
            ->select();
        
        // 获取客户产品溯源记录
        $traceabilities = \app\admin\model\scanwork\Traceability::where('customer_id', $ids)
            ->order('createtime desc')
            ->limit(10)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('stats', $stats);
        $this->view->assign('orders', $orders);
        $this->view->assign('traceabilities', $traceabilities);
        
        return $this->view->fetch();
    }

    /**
     * 生成客户编码
     */
    private function generateCustomerCode()
    {
        $prefix = 'KH-' . date('Y') . '-';
        $lastCode = $this->model->where('customer_code', 'like', $prefix . '%')
            ->order('customer_code desc')
            ->value('customer_code');
        
        if ($lastCode) {
            $lastNumber = intval(substr($lastCode, -3));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        return $prefix . str_pad($newNumber, 3, '0', STR_PAD_LEFT);
    }

    /**
     * 获取客户列表（用于下拉选择）
     */
    public function getCustomerList()
    {
        $list = $this->model->where('status', 1)->column('customer_name', 'id');
        $this->success('', null, $list);
    }

    /**
     * 更新客户订单历史
     */
    public function updateOrderHistory($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $customer = $this->model->get($ids);
        if (!$customer) {
            $this->error('客户不存在');
        }
        
        try {
            $customer->updateOrderHistory();
            $this->success('订单历史更新成功');
        } catch (Exception $e) {
            $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 批量导入客户
     */
    public function import()
    {
        if ($this->request->isPost()) {
            $file = $this->request->file('file');
            if (!$file) {
                $this->error('请选择文件');
            }
            
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
            if (!in_array($ext, ['xlsx', 'xls'])) {
                $this->error('文件格式错误，请上传Excel文件');
            }
            
            try {
                // 使用PhpSpreadsheet读取Excel
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getPathname());
                $worksheet = $spreadsheet->getActiveSheet();
                $data = $worksheet->toArray();
                
                // 过滤空行
                $validData = [];
                foreach ($data as $row) {
                    if (!empty(array_filter($row, function($cell) { return !is_null($cell) && $cell !== ''; }))) {
                        $validData[] = $row;
                    }
                }
                
                if (count($validData) < 2) {
                    $this->error('Excel文件数据不足');
                }
                
                $successCount = 0;
                $errorCount = 0;
                $errors = [];
                
                Db::startTrans();
                try {
                    // 从第二行开始处理数据（第一行是标题）
                    for ($i = 1; $i < count($validData); $i++) {
                        $row = $validData[$i];
                        
                        if (empty($row[0])) { // 客户名称不能为空
                            $errorCount++;
                            $errors[] = "第" . ($i + 1) . "行：客户名称不能为空";
                            continue;
                        }
                        
                        $customerData = [
                            'customer_name' => trim($row[0]),
                            'contact_person' => isset($row[1]) ? trim($row[1]) : '',
                            'contact_phone' => isset($row[2]) ? trim($row[2]) : '',
                            'contact_email' => isset($row[3]) ? trim($row[3]) : '',
                            'address' => isset($row[4]) ? trim($row[4]) : '',
                            'special_requirements' => isset($row[5]) ? trim($row[5]) : '',
                            'status' => 1,
                            'createtime' => time()
                        ];
                        
                        // 生成客户编码
                        $customerData['customer_code'] = $this->generateCustomerCode();
                        
                        // 检查客户名称是否已存在
                        if ($this->model->where('customer_name', $customerData['customer_name'])->find()) {
                            $errorCount++;
                            $errors[] = "第" . ($i + 1) . "行：客户名称【{$customerData['customer_name']}】已存在";
                            continue;
                        }
                        
                        $this->model->create($customerData);
                        $successCount++;
                    }
                    
                    Db::commit();
                    $message = "导入完成！成功：{$successCount}条，失败：{$errorCount}条";
                    if (!empty($errors)) {
                        $message .= "\n错误详情：\n" . implode("\n", $errors);
                    }
                    $this->success($message);
                    
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('导入失败：' . $e->getMessage());
                }
                
            } catch (Exception $e) {
                $this->error('文件读取失败：' . $e->getMessage());
            }
        }
        
        return $this->view->fetch();
    }

    /**
     * 下载导入模板
     */
    public function downloadTemplate()
    {
        try {
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置标题
            $sheet->setCellValue('A1', '客户信息导入模板');
            $sheet->mergeCells('A1:F1');
            
            // 设置表头
            $sheet->setCellValue('A2', '客户名称*');
            $sheet->setCellValue('B2', '对接人');
            $sheet->setCellValue('C2', '联系电话');
            $sheet->setCellValue('D2', '联系邮箱');
            $sheet->setCellValue('E2', '客户地址');
            $sheet->setCellValue('F2', '特殊生产要求');
            
            // 设置示例数据
            $sheet->setCellValue('A3', '青岛豪而美工贸有限公司');
            $sheet->setCellValue('B3', '张经理');
            $sheet->setCellValue('C3', '13800138001');
            $sheet->setCellValue('D3', 'zhang@haomei.com');
            $sheet->setCellValue('E3', '青岛市市南区香港中路100号');
            $sheet->setCellValue('F3', '产品需印专属logo，采用哑光抛光工艺');
            
            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(25);
            $sheet->getColumnDimension('B')->setWidth(15);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(25);
            $sheet->getColumnDimension('E')->setWidth(30);
            $sheet->getColumnDimension('F')->setWidth(35);
            
            // 设置样式
            $sheet->getStyle('A1:F1')->getFont()->setBold(true)->setSize(14);
            $sheet->getStyle('A2:F2')->getFont()->setBold(true);
            $sheet->getStyle('A2:F2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
            
            // 设置边框
            $sheet->getStyle('A2:F3')->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
            
            // 输出文件
            $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
            $filename = '客户信息导入模板_' . date('YmdHis') . '.xlsx';
            
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $filename . '"');
            header('Cache-Control: max-age=0');
            
            $writer->save('php://output');
            exit;
            
        } catch (Exception $e) {
            $this->error('模板生成失败：' . $e->getMessage());
        }
    }
}
